package org.example.managementsystem.controller;

import org.example.managementsystem.model.Device;
import org.example.managementsystem.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 设备管理控制器
 */
@RestController
@RequestMapping("/api/devices")
public class DeviceController {
    private final DeviceService deviceService;

    @Autowired
    public DeviceController(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    /**
     * 添加设备
     */
    @PostMapping
    public ResponseEntity<Device> addDevice(@RequestBody Device device) {
        Device savedDevice = deviceService.addDevice(device);
        return ResponseEntity.ok(savedDevice);
    }

    /**
     * 批量更新空设备编号
     */
    @PostMapping("/batch-update-numbers")
    public ResponseEntity<Integer> batchUpdateEmptyDeviceNumbers() {
        int updatedCount = deviceService.batchUpdateEmptyDeviceNumbers();
        return ResponseEntity.ok(updatedCount);
    }

    /**
     * 更新设备
     */
    @PutMapping("/{id}")
    public ResponseEntity<Device> updateDevice(@PathVariable Long id, @RequestBody Device device) {
        device.setId(id);
        boolean updated = deviceService.updateDevice(device);
        if (updated) {
            return ResponseEntity.ok(device);
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDevice(@PathVariable Long id) {
        boolean deleted = deviceService.deleteDevice(id);
        if (deleted) {
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 根据ID查询设备
     */
    @GetMapping("/{id}")
    public ResponseEntity<Device> getDeviceById(@PathVariable Long id) {
        Device device = deviceService.getDeviceById(id);
        if (device != null) {
            return ResponseEntity.ok(device);
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 查询所有设备
     */
    @GetMapping
    public ResponseEntity<List<Device>> getAllDevices() {
        List<Device> devices = deviceService.getAllDevices();
        return ResponseEntity.ok(devices);
    }

    /**
     * 搜索设备
     */
    @GetMapping("/search")
    public ResponseEntity<List<Device>> searchDevices(@RequestParam String keyword) {
        List<Device> devices = deviceService.searchDevices(keyword);
        return ResponseEntity.ok(devices);
    }
}
